package com.nb82.bean.im.pro;
import java.nio.ByteOrder;
import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;


public class Encode extends ProtocolEncoderAdapter {
  private Charset charset = null;

  public Encode(Charset charset) {
    this.charset = charset;
  }

  @Override
  public void encode(IoSession session, Object message,
      ProtocolEncoderOutput out) throws Exception {
    if (message instanceof PackageHead) {
      PackageHead ph = (PackageHead) message;
      IoBuffer buf = IoBuffer.allocate(ph.getPackageHeadLength() + ph.getPackageBodyLength());
      buf.order(ByteOrder.LITTLE_ENDIAN);
      //buf.setAutoExpand(true);
      buf.putShort((short) ph.getPackageHeadLength());
      buf.put((byte) ph.getMessageType());
      buf.put((byte) ph.getContentType());
      buf.putShort((short) ph.getMessageCommand());
      buf.putInt((int) ph.getPackageBodyLength());
      if (ph.getPackageBodyLength() > 0) {
        buf.putString(ph.getPackageBodyContent(), charset.newEncoder());
      }
      buf.flip();
      out.write(buf);
      out.flush();
      buf.free();
    }
  }
}
